<template>
  <div class="materialAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(serviceFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>

    <div class="material-title" v-if="titleShow">
      <span class="circle"></span>
      <span class="collapse-title"
        >{{
          pageType !== "detail" ? (pageType === "add" ? "新增" : "编辑") : ""
        }}维修记录</span
      >
    </div>
    <div class="material-info">
      <el-form
        :model="serviceForm"
        ref="serviceFormRef"
        :rules="queryRules"
        label-width="120"
        v-enterToNext
        :disabled="pageType === 'detail'"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="上传人:">
              <el-input
                v-model="serviceForm.uploadPersonnel"
                placeholder="自动生成"
                clearable
                class="search-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上传时间" prop="saleName" label-width="134">
              <el-date-picker
                v-model="serviceForm.uploadTime"
                class="search-input"
                type="datetime"
                placeholder="保存时自动获取当前时间"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:">
              <el-input
                style="width: 100%"
                maxlength="2000"
                v-model="serviceForm.remark"
                type="textarea"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="上传文件:" prop="uploadFile">
              <Upload
                :fileList="serviceForm.uploadFile"
                :isFull="true"
                :isCanDelete="pageType == 'detail' ? false : true"
                :disabled="pageType == 'detail'"
                accept=".doc,.docx,.pdf,.jpg,.png"
                :showButton="serviceForm.uploadFile.length == 0"
                limitation="nolimit"
                :limit="1"
                @success="(result) => uploadSuccess(result)"
                @deleteFile="(result) => uploadRemove(result)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import { getDictsApi } from "@/api/dict";
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
import { ElMessage, ElMessageBox } from "element-plus";
import { getMaterialClassListApi } from "@/api/information/materialClass";
import { getfixAddApi } from "@/api/operation/productLibrary.js";
import {
  getMaterialApi,
  getPurchasePriceApi,
} from "@/api/information/material";
import useUserStore from "@/store/modules/user";
//当前用户信息
const userStore = useUserStore();
const emit = defineEmits([
  // 物料新增组件显隐
  "ServiceAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  // 操作类型
  titleShow: {
    type: Boolean,
    default: false,
  },
  FormTemplate: {
    type: Object,
    default: {
      uploadFile: [],
    },
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 物料表单引用
const serviceFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 单位列表
const unitList = ref([]);
// 存货类型列表
const stockTypeList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 默认税率列表
const taxRateList = ref([]);
// 销售单价初始值
const purchasePrice = ref(null);
// 部门列表
const deptOptions = ref(undefined);

// 物料表单数据模板
const SeviceFormTemplate = {
  uploadPersonnel: userStore.name,
  uploadTime: "",
  remark: "",
  uploadFile: [],
};
const data = reactive({
  // 物料表单
  serviceForm: JSON.parse(JSON.stringify(SeviceFormTemplate)),
  // 物料表单校验规则
  queryRules: {
    uploadFile: [{ required: true, message: "请上传文件", trigger: "change" }],
  },

  flagList: [
    {
      label: "是",
      value: 1,
    },
    {
      label: "否",
      value: 0,
    },
  ],
  classOptions: [],
});
const { serviceForm, queryRules, flagList, classOptions } = toRefs(data);

watch(
  () => props.FormTemplate,
  (newValue, oldValue) => {
    serviceForm.value = JSON.parse(JSON.stringify(newValue));
    serviceForm.value.uploadPersonnel = userStore.name;
  },
  { deep: true, immediate: true }
);

/**
 * @description: 保存
 * @param {Object} serviceFormRef 物料表单引用
 */
const handleAddSave = async (serviceFormRef) => {
  if (!serviceFormRef) return;
  await serviceFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          const currentDate = new Date(Date.now()); // 使用时间戳创建日期对象
          const year = currentDate.getFullYear().toString(); // 获取年份的最后两位
          const month = (currentDate.getMonth() + 1)
            .toString()
            .padStart(2, "0"); // 月份从0开始，保证两位数格式
          const day = currentDate.getDate().toString().padStart(2, "0"); // 保证两位数格式
          const hours = currentDate.getHours().toString().padStart(2, "0"); // 保证两位数格式
          const minutes = currentDate.getMinutes().toString().padStart(2, "0"); // 保证两位数格式
          const seconds = currentDate.getSeconds().toString().padStart(2, "0"); // 保证两位数格式

          const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
          serviceForm.value.uploadTime = formattedDateTime;
          serviceForm.value.name = serviceForm.value.uploadFile[0].name;
          serviceForm.value.fileExtension =
            serviceForm.value.uploadFile[0].fileExtension;
          serviceForm.value.url = serviceForm.value.uploadFile[0].url;
          const res = await getfixAddApi(serviceForm.value);
          if (res.code === 200) {
            emit("update:ServiceAddShow", false);
            emit("refreshList", true);
            ElMessage.success(res.msg);
            serviceForm.value = JSON.parse(JSON.stringify(SeviceFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};
/**
 * @description: 维修id处理
 */
const handlemaintenance = (droneId) => {
  serviceForm.value.droneId = droneId;
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  serviceForm.value.uploadFile.push({ ...response, businessType: 4 });
  serviceFormRef.value.validateField("uploadFile");
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  serviceForm.value.uploadFile.splice(index, 1);
}

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:ServiceAddShow", false);
    serviceForm.value = JSON.parse(JSON.stringify(SeviceFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:ServiceAddShow", false);
        serviceForm.value = JSON.parse(JSON.stringify(SeviceFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 部门列表
  await deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getMaterialApi(id);
    const purchaseRes = await getPurchasePriceApi(id);
    serviceForm.value = res.data;
    purchasePrice.value = res.data.price;
    serviceForm.value.reason = "";
    serviceForm.value.tableData = purchaseRes || [];
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 处理供应商、生产厂家选择
 */
const handleSuppliereSelect = (value, type) => {
  switch (type) {
    case 1:
      serviceForm.value.supplierId = value.supplierId;
      break;
    case 2:
      serviceForm.value.manufacturerId = value.supplierId;
      break;
    default:
      break;
  }
};

onMounted(() => {
  getDicts();
  // nextTick(() => {
  //   refInput.value.focus(); // 聚焦
  // });
});

const querySearch = (queryString, cb) => {
  const results = queryString
    ? suppliereList.value.filter(createFilter(queryString))
    : suppliereList.value;
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

defineExpose({
  handleDetailInfo,
  handlemaintenance,
});
</script>
<style>
.autocomplete-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
<style lang="scss" scoped>
.materialAdd {
  padding: 20px 20px 0 20px;
  width: 100%;
  height: 100%;
  .el-collapse,
  .el-collapse-item__wrap {
    border: none;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .material-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .material-title {
    display: flex;
    align-items: center;
    width: 100%;
    height: 48px;
    background-color: #f8faff;
  }
  .contact-info {
    padding-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-around;
      .table-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: center;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
</style>
